package cn.edu.swu.lxy.rolems.adapter

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cn.edu.swu.lxy.rolems.Role
import cn.edu.swu.lxy.rolems.MyDatabaseHelperRole
import cn.edu.swu.lxy.rolems.R

class RolesAdapter(private val context: Context, private val rolesList: List<Role>) :
    RecyclerView.Adapter<RolesAdapter.ViewHolder>() {
    private val dbHelper: MyDatabaseHelperRole = MyDatabaseHelperRole(context, "Roles.db", 2)
    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val itemImage: ImageView = view.findViewById(R.id.itemImage)
        val itemName: TextView = view.findViewById(R.id.itemName)
        val itemAttr: TextView = view.findViewById(R.id.itemAttr)
        val itemPs: TextView = view.findViewById(R.id.itemPs)
        val itemBtn: Button = view.findViewById(R.id.btn)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.role, parent, false)
        return ViewHolder(view)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = rolesList[position]
        holder.itemImage.setImageResource(item.imageId)
        holder.itemName.text = item.name
        holder.itemAttr.text = "角色属性: "+item.attr+"元素"
        holder.itemPs.text = item.ps
        holder.itemBtn.setOnClickListener {
            val db = dbHelper.writableDatabase
            val values = ContentValues().apply {
                put("name", item.name)
                put("attr", item.attr)
                put("ps", item.ps)
                put("pic", item.imageId)
            }
            db.insert("MyRoles", null, values)
        }
    }
    override fun getItemCount() = rolesList.size
}